<template>
  <div class="history-container">
    <div class="container">
      <h1 class="page-title">观看历史</h1>
      
      <div v-if="historyItems.length > 0" class="history-content">
        <div class="history-controls">
          <button class="btn btn-danger" @click="clearAllHistory">清空历史记录</button>
        </div>
        
        <div class="history-list">
          <div v-for="item in historyItems" :key="item.id" class="history-item">
            <div class="history-video-info">
              <router-link :to="`/video/${item.id}`" class="video-thumbnail">
                <img :src="item.thumbnail || '/placeholder.jpg'" :alt="item.title" />
                <span class="video-duration">{{ formatDuration(item.duration) }}</span>
              </router-link>
              
              <div class="video-details">
                <router-link :to="`/video/${item.id}`" class="video-title">{{ item.title }}</router-link>
                <div class="video-meta">
                  <span class="video-author">{{ item.author }}</span>
                  <span class="video-views">{{ formatNumber(item.views) }} 次观看</span>
                  <span class="view-time">{{ formatDate(item.viewTime) }}</span>
                </div>
                <div class="progress-container">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: item.watchProgress + '%' }"></div>
                  </div>
                  <span class="progress-text">{{ formatDuration(item.watchTime) }} / {{ formatDuration(item.duration) }}</span>
                </div>
              </div>
            </div>
            
            <button class="btn-remove" @click="removeFromHistory(item.id)" title="移除记录">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-history">
        <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="12" cy="12" r="10"></circle>
          <polyline points="12 6 12 12 16 14"></polyline>
        </svg>
        <p>暂无观看历史</p>
        <router-link to="/" class="btn btn-primary">去首页看看</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { isLoggedIn } from '../services/auth'

const router = useRouter()
const historyItems = ref([])

// 模拟历史记录数据
const mockHistoryItems = [
  {
    id: '1',
    title: 'Vue.js 3 入门教程：组合式 API 详解',
    author: '技术课堂',
    thumbnail: '/favicon.ico',
    duration: 1280,
    watchTime: 450,
    watchProgress: 35,
    views: 12500,
    viewTime: new Date(Date.now() - 3600000)
  },
  {
    id: '2',
    title: 'JavaScript 异步编程实战指南',
    author: '前端学院',
    thumbnail: '/favicon.ico',
    duration: 1800,
    watchTime: 1800,
    watchProgress: 100,
    views: 8900,
    viewTime: new Date(Date.now() - 86400000)
  },
  {
    id: '3',
    title: 'CSS Grid 布局完全指南',
    author: '设计与前端',
    thumbnail: '/favicon.ico',
    duration: 1560,
    watchTime: 780,
    watchProgress: 50,
    views: 15600,
    viewTime: new Date(Date.now() - 172800000)
  }
]

onMounted(() => {
  // 检查用户登录状态
  if (!isLoggedIn()) {
    router.push({ name: 'login', query: { redirect: '/user/history' } })
    return
  }
  
  // 这里应该从API获取历史记录，现在使用模拟数据
  historyItems.value = mockHistoryItems
})

// 格式化时长
function formatDuration(seconds) {
  const hrs = Math.floor(seconds / 3600)
  const mins = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hrs > 0) {
    return `${hrs}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 格式化日期
function formatDate(date) {
  const now = new Date()
  const diff = now - new Date(date)
  
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)} 分钟前`
  }
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)} 小时前`
  }
  // 小于7天
  if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)} 天前`
  }
  // 超过7天显示具体日期
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化数字
function formatNumber(num) {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

// 从历史记录中移除单个项目
function removeFromHistory(id) {
  const index = historyItems.value.findIndex(item => item.id === id)
  if (index !== -1) {
    historyItems.value.splice(index, 1)
    // 这里应该调用API删除历史记录
  }
}

// 清空所有历史记录
function clearAllHistory() {
  if (confirm('确定要清空所有观看历史吗？此操作不可恢复。')) {
    historyItems.value = []
    // 这里应该调用API清空历史记录
  }
}
</script>

<style scoped>
.history-container {
  padding: 20px 0;
  min-height: calc(100vh - 200px);
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 30px;
  color: #333;
}

.history-controls {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.history-item {
  display: flex;
  align-items: flex-start;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.history-video-info {
  flex: 1;
  display: flex;
  gap: 15px;
}

.video-thumbnail {
  position: relative;
  width: 240px;
  height: 135px;
  border-radius: 6px;
  overflow: hidden;
  display: block;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-duration {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 500;
}

.video-details {
  flex: 1;
  min-width: 0;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  text-decoration: none;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.video-title:hover {
  color: #007bff;
}

.video-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #eee;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #007bff;
  border-radius: 3px;
  transition: width 0.3s;
}

.progress-text {
  font-size: 12px;
  color: #999;
  min-width: 120px;
}

.btn-remove {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.2s;
}

.btn-remove:hover {
  background: #f5f5f5;
  color: #ff4757;
}

.empty-history {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-history svg {
  color: #ccc;
  margin-bottom: 20px;
}

.empty-history p {
  font-size: 16px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .history-video-info {
    flex-direction: column;
  }
  
  .video-thumbnail {
    width: 100%;
    height: auto;
    aspect-ratio: 16/9;
  }
  
  .video-meta {
    flex-direction: column;
    gap: 5px;
  }
  
  .progress-container {
    flex-direction: column;
    align-items: stretch;
    gap: 5px;
  }
  
  .progress-text {
    text-align: right;
  }
}
</style>